﻿using GYCTOAManagementSystemNewApi.Model;
using GYCTOAManagementSystemNewApi.Model.Tool;
using GYCTOAManagementSystemNewApi.Model.ViewModel;
using GYCTOAManagementSystemNewApi.Public;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using MongoDB.Bson;
using MongoDB.Driver;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Threading.Tasks;
using System.Transactions;

namespace GYCTOAManagementSystemNewApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    [Authorize]
    public class MessageTableController : Controller
    {
        DBContext db = null;
        // GET: MessageTable
        public MessageTableController(DBContext _DBContext)
        {
            db = _DBContext;
        }
        /// <summary>
        /// 初始化数据加载/查询
        /// </summary>
        /// <param name="limit"></param>
        /// <param name="offset"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        [HttpPost("MessageData")]
        public JsonResult MessageData([FromBody] dynamic formData)          
        {
            //(int limit, int offset, string start = "", string end = "", string MessageType = "", int State = -1)
            JToken j_token = JsonConvert.DeserializeObject<JToken>(formData.ToString());
            int offset = Convert.ToInt32(j_token["currentPage"]);
            int limit = Convert.ToInt32(j_token["pagesize"]);
            var from = j_token["from"];

            var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ');
            var TokenValuesArray = TokenManage.GetTokenValues(author[1]);
            var id = TokenValuesArray[0].Value.Split(':')[0];//当前账户ID
            string sql = "";
            if (id=="1")
            {

                sql += "SELECT * FROM `messageTable` WHERE `Delete` = 0 ";
            }
            else
            {
                sql += "SELECT * FROM `messageTable` WHERE `Delete` = 0 AND `Receiver`=" + id + "";
            }

            var lis = db.MessageTable.FromSqlRaw(sql).OrderBy(x => x.State).ThenByDescending(x => x.CreateTime).ToList();
            if (from["State"].ToString() != "")
            {
                int newState = Convert.ToInt32(from["State"].ToString());
                lis = lis.Where(x => x.State == newState).ToList();
            } 
            if (from["MessageType"].ToString()  != "")
            {
                int ad = Convert.ToInt32(from["MessageType"].ToString());
                lis = lis.Where(x => x.MessageType == ad).ToList();
            }
            if (from["start"].ToString() != "")
            {
                var newstart = Convert.ToDateTime(from["start"].ToString());
                lis = lis.Where(x => x.CreateTime >= newstart).ToList();
            }
            if (from["end"].ToString() != "")
            {
                var newend = Convert.ToDateTime(from["end"].ToString()).AddDays(1);
                lis = lis.Where(x => x.CreateTime <= newend).ToList();
            }
            var total = lis.Count;
            int noread = lis.Where(x=>x.State.Equals(0)).Count();
            var rows = lis.Skip(limit * (offset - 1)).Take(limit).ToList();
            return Json(new { code = 0, msg = "", count = total, data = rows, noread = noread });
        }
        /// <summary>
        /// 删除对应消息记录
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost("MessageDel")]
        public JsonResult MessageDel(int[] ids)
        {
            if (ids != null)
            {
                foreach (var item in ids)
                {
                    var res = db.MessageTable.Where(x => x.Id == item).FirstOrDefault();
                    res.Delete = true;
                }
            }
            bool result = db.SaveChanges() > 0 ? true : false;
            return Json(new { res = result });
        }
       
        /// <summary>
        /// 检测消息管理的跳转时候具有权限
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        [HttpGet("UrlTesting")]
        public JsonResult UrlTesting(string url)
        {
            var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ');
            var TokenValuesArray = TokenManage.GetTokenValues(author[1]);
            var useid = TokenValuesArray[0].Value.Split(':')[0];//当前账户ID
            Users users = db.Users.Where(x => x.Id.ToString() == useid).FirstOrDefault();
            string[] roleid = users.RoleId.Split(',');
            List<string> num_lis = new List<string>();
            foreach (var item in roleid)
            {
                int role = Convert.ToInt32(item);
                var roledata = db.Role.Where(x => x.Id == role).FirstOrDefault().RoleNumber.Split(',');
                foreach (var a in roledata)
                {
                    num_lis.Add(a);
                }
            }
            string strcon = ConfigurationManager.ConnectionStrings["mongo_con"].ConnectionString;
            MongoClient client = new MongoClient(strcon);
            var clientdb = client.GetDatabase("oalist");
            var collection = clientdb.GetCollection<BsonDocument>("menu_lists");
            List<BsonDocument> list = collection.Find(new BsonDocument()).ToList();
            List<Menu_lists> menuListses = new List<Menu_lists>();
            for (int i = 0; i < list.Count; i++)
            {
                if (list[i].Contains("role"))
                {
                    if (list[i]["role"].IsBsonArray)
                    {
                        var lisArray = list[i]["role"].AsBsonArray;
                        for (int j = 0; j < lisArray.Count; j++)
                        {
                            BsonDocument str = lisArray[j].AsBsonDocument;
                            Menu_lists menu = new Menu_lists();
                            menu.Roid = str["roid"].AsString;
                            menu.Url = str["url"].AsString;
                            menu.Name = str["name"].AsString;
                            menu.Index = Convert.ToInt32(str["index"]); //str["index"].AsInt32;
                            menuListses.Add(menu);
                        }
                    }
                }
            }
            var mangoid = menuListses.Where(x => x.Url == url).FirstOrDefault();
            bool result = num_lis.Contains(mangoid.Roid);
            return Json(new { result = result, name = mangoid.Name, roid = mangoid.Roid + 1 });
        }

        /// <summary>
        /// 修改未读状态
        /// </summary>
        /// <param name="ids">id数组</param>
        /// <returns></returns>
        [HttpPost("UpdateState")]
        public JsonResult UpdateState(int[] ids)
        {
            Message message = new Message();
            message.IsSuccess = false;
            message.Msg = "修改失败,请重试!";
            using (var scope = new TransactionScope())
            { 
                if (ids != null)
                {
                    foreach (var item in ids)
                    {
                        var res = db.MessageTable.Where(x => x.Id == item).FirstOrDefault();
                        res.State = 1;
                        res.ReadTime = DateTime.Now;
                    }
                    message.IsSuccess = db.SaveChanges() > 0 ? true : false;
                    message.Msg = message.IsSuccess ? "修改成功!" : "修改失败,请重试!";
                }
                //提交事务
                scope.Complete();
            }
            return new JsonResult( new{ mes = message });
        }

        /// <summary>
        /// 全部已读
        /// </summary>
        /// <returns></returns>
        [HttpGet("AllRead")]
        public JsonResult AllRead()
        {
            Message message = new Message();
            message.IsSuccess = false;
            var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];
            var logid = Convert.ToInt32(TokenManage.GetTokenValues(author)[0].Value) ;
            var notlis = db.MessageTable.Where(x => x.Receiver.Equals(logid) && x.State.Equals(0) && !x.Delete).ToList();
            foreach (var item in notlis)
            {
                item.State = 1;
            }
            message.IsSuccess = db.SaveChanges() > 0 ? true : false;
            message.Msg = message.IsSuccess ? "全部已读!" : "修改失败,请重试!";
            return new JsonResult(new { mes = message });
        }
    }
}
